#include "hal_api.h"
#include "printf.h"

#define SENSOR_I2C_ADDR         0x40

#define T_MEASUREMENT_CMD       0xE3
#define RH_MEASUREMENT_CMD      0xE5
#define RESET_CMD               0xFE

#define MEASURE_TIMES           3
static int32_t tsensor_send_cmd(I2c_Id i2c, uint8_t cmd)
{
	int32_t ret;
	ret = Hal_I2c_Write(i2c, &cmd, 1);
	return ret;
}

static int32_t tsensor_read_data(I2c_Id i2c, uint16_t *data)
{
	int32_t ret;
	uint8_t buf[3];
	ret = Hal_I2c_Read(i2c, buf, 3);
	if (ret) {
		return ret;
	}
	*data = ((uint16_t)(buf[0]) << 8) + (buf[1] & 0xFE);
	return ret;
}


int32_t test_tsensor(void)
{
	int ret;
	int index;
	uint16_t t_data, rh_data;
	printf("\r\n[TSENSOR]: TEST START\r\n");
	ret = Hal_I2c_Tar_Add_Cfg(I2C_ID_0, SENSOR_I2C_ADDR);
	if (ret) {
		printf("[TSENSOR]: set i2c device addr err\r\n");
		return ret;
	}
	ret = tsensor_send_cmd(I2C_ID_0, RESET_CMD);
	if (ret) {
		printf("[TSENSOR]: send reset cmd err\r\n");
		return ret;
	}
	Hal_Cnt_DelayMs(100);
	for (index = 0; index < MEASURE_TIMES; index++)
	{
		ret = tsensor_send_cmd(I2C_ID_0, T_MEASUREMENT_CMD);
		if (ret) {
			printf("[TSENSOR]: send t_cmd err\r\n");
			return ret;
		}
		ret = tsensor_read_data(I2C_ID_0, &t_data);
		if (ret) {
			printf("[TSENSOR]: get t_data err\r\n");
			return ret;
		}
		Hal_Cnt_DelayMs(10);
		ret = tsensor_send_cmd(I2C_ID_0, RH_MEASUREMENT_CMD);
		if (ret) {
			printf("[TSENSOR]: send rh_cmd err\r\n");
			return ret;
		}
		ret = tsensor_read_data(I2C_ID_0, &rh_data);
		if (ret) {
			printf("[TSENSOR]: get rh_data err\r\n");
			return ret;
		}
		Hal_Cnt_DelayMs(2000);

		printf("[TSENSOR]: the cur temp value is %.2f\r\n", t_data *175.72f / 65536 - 46.85f);
		printf("[TSENSOR]: the cur rh value is %.2f%%\r\n", rh_data *125.0f / 65536 - 6.0f);
	}
	printf("\r\n[TSENSOR]: TEST END\r\n");

	return ret;
}

